use std::{collections::HashMap, env, sync::OnceLock};

use once_cell::sync::OnceCell;
#[cfg(target_os = "macos")]
use tauri::menu::PredefinedMenuItem;
use tauri::{
    menu::{Menu, MenuItem},
    Manager, PhysicalPosition, WebviewUrl, WebviewWindowBuilder,
};

use crate::service::window_service;

mod dao;
mod hot_key;
mod service;
mod tray;
mod utils;

pub static PHYSIZE: OnceCell<HashMap<String, u32>> = OnceCell::new();
pub static mut SCALE_FACTOR: f64 = 0.0;
pub static APP_DIR: OnceLock<String> = OnceLock::new();
pub static FILE_DATA_BASE_PATH: OnceLock<String> = OnceLock::new();

#[tokio::main]
async fn init(handle: &tauri::AppHandle) {
    let path: std::path::PathBuf = handle.path().app_data_dir().unwrap();
    if let Some(path_str) = path.to_str() {
        let path_string = path_str.to_string();
        log::info!("mysql");
        println!("路径为: {}", path_string);
        crate::utils::mysql_utils::init_mysql_pool("mydatabase.db", path_string).await;
    } else {
        handle.exit(0);
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_positioner::init())
        .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
            window_service::open_window(
                app,
                "editor-123".to_string(),
                "文本编辑".to_string(),
                "/editor".to_string(),
            );
        }))
        .plugin(tauri_plugin_persisted_scope::init())
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_clipboard_manager::init())
        .plugin(tauri_plugin_sql::Builder::new().build())
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_fs::init())
        // .menu(|handle| {
        //     Menu::with_items(
        //         handle,
        //         &[
        //             #[cfg(target_os = "macos")]
        //             &Submenu::with_items(
        //                 handle,
        //                 "rcr",
        //                 true,
        //                 &[
        //                     &MenuItem::new(handle, "关于", true, None::<&str>)?,
        //                     &MenuItem::new(handle, "你好", true, None::<&str>)?,
        //                     &PredefinedMenuItem::close_window(handle, Some("退出"))?,
        //                 ],
        //             )?,
        //             #[cfg(target_os = "macos")]
        //             &Submenu::with_items(
        //                 handle,
        //                 "文件",
        //                 true,
        //                 &[
        //                     #[cfg(target_os = "macos")]
        //                     &MenuItem::new(handle, "你好", true, None::<&str>)?,
        //                 ],
        //             )?,
        //         ],
        //     )
        // })
        .setup(|app| {
            init(app.handle());

            let handle = app.handle();
            let path = env::current_exe()
                .map(|p| {
                    p.parent()
                        .map(|dir| dir.to_string_lossy().to_string())
                        .unwrap_or_else(|| "unknown parent".to_string())
                })
                .unwrap_or_else(|_| "unknown path".to_string());
            println!("执行路径: {}", path);
            APP_DIR.set(path.clone()).ok();
            FILE_DATA_BASE_PATH.set(path + "/database").ok();

            tray::create_tray(handle)?;

            // 定义菜单
            //let save_menu_item = MenuItem::new(handle, "保存", true, None::<&str>)?;
            //#[cfg(target_os = "macos")]
            // {

            //     let save_menu = Submenu::new(handle, "保存", true)?;
            //     let menu = Menu::with_items(
            //         handle,
            //         &[&Submenu::with_items(
            //             handle,
            //             "文件",
            //             true,
            //             &[&save_menu_item],
            //         )?],
            //     )?;
            // }

            let win_builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default());
            let mut w = 673.0;
            let mut h = 500.0;
            w = 970.0;
            h = 670.0;
            let win_builder = win_builder
                .title("MOMENTO")
                .inner_size(w, h)
                .disable_drag_drop_handler()
                //.devtools(true)
                //.always_on_top(true)
                ;
            #[cfg(target_os = "windows")]
            let win_builder = win_builder.visible(false);
            //et win_builder = win_builder.menu(menu);

            // 仅在 macOS 时设置透明标题栏
            #[cfg(target_os = "macos")]
            use tauri::TitleBarStyle;
            #[cfg(target_os = "macos")]
            let win_builder = win_builder.title_bar_style(TitleBarStyle::Transparent);

            let window = win_builder.build();
            match window {
                Ok(window) => {
                    // 获取主窗口所在的屏幕
                    if let Some(monitor) = window.primary_monitor().unwrap() {
                        let size = monitor.size();
                        let width = size.width;
                        let height = size.height;
                        unsafe { SCALE_FACTOR = monitor.scale_factor() };
                        let mut map: HashMap<String, u32> = HashMap::new();
                        map.insert(String::from("width"), width);
                        map.insert(String::from("height"), height);

                        log::info!("scale_factor: {}", monitor.scale_factor());

                        PHYSIZE
                            .set(map)
                            .unwrap_or_else(|_| println!("try insert pool cell failure!"));

                        let width = (width as f64 / monitor.scale_factor() - w) / 2.0;
                        let height = (height as f64 / monitor.scale_factor() - h) / 2.0;

                        let _ = window.set_position(PhysicalPosition::new(width, height));
                        //let _ = window.set_always_on_top(false);
                        log::info!("Screen resolution: {}x{}", width, height);
                    } else {
                        log::info!("Could not get monitor information");
                    }
                    // 仅在构建 macOS 时设置背景颜色
                    // #[cfg(target_os = "macos")]
                    // {
                    //     use objc2_app_kit::NSWindow;
                    //     use objc2_app_kit::NSColor;
                    //     let ns_window_ptr = window.ns_window().unwrap() as *mut NSWindow;
                    //     unsafe {
                    //         (*ns_window_ptr).setOpaque(false);
                    //         let clear_color = NSColor::clearColor();
                    //         (*ns_window_ptr).setBackgroundColor(Some(clear_color.as_ref()));
                    //     }
                    // }
               
                }
                Err(e) => {
                    log::error!("构建错误！ {}", e);
                }
            }

            #[cfg(desktop)]
            {
                //自启动
                use tauri_plugin_autostart::MacosLauncher;
                use tauri_plugin_autostart::ManagerExt;

                let _ = app.handle().plugin(tauri_plugin_autostart::init(
                    MacosLauncher::LaunchAgent,
                    Some(vec![]),
                ));

                // Get the autostart manager
                let autostart_manager = app.autolaunch();
                // Enable autostart
                let _ = autostart_manager.enable();
            }

            let _ = hot_key::create_host_key(handle);

            #[cfg(debug_assertions)] // 只在开发模式开启
            {
                let window = app.get_webview_window("main").unwrap();
                window.open_devtools(); // 自动打开开发者工具
                // window.close_devtools(); // 关闭开发者工具
            }

            Ok(())
        })
        .plugin(tauri_plugin_os::init())
        .on_window_event(|window, event| match event {
            tauri::WindowEvent::CloseRequested { api, .. } => {
                let label = window.label();
                if label.eq("main") {
                    api.prevent_close();
                    let _ = window.hide();
                }
            }
            _ => {}
        })
        .invoke_handler(tauri::generate_handler![
            service::file_service::read_file,
            service::file_service::write_file,
            service::file_service::del_file,
            service::file_service::copy_file,
            service::file_service::file_exists,
            service::file_service::upload_file,
            
            service::momento_service::add_momento,
            service::momento_service::save_momento,
            service::momento_service::update_momento,
            service::momento_service::update_momento_sort,
            service::momento_service::update_momento_title_heading,
            service::momento_service::update_momento_content,
            service::momento_service::delete_momento,
            service::momento_service::get_momento_list,
            service::momento_service::get_momento_tree,
            service::momento_service::get_info_by_id,

            service::window_service::open_editor_momento,
            service::window_service::get_cache_str,
            service::window_service::save_clipboard_img,

            service::book_name_service::book_name_list,
            service::book_name_service::save_book_name,
            service::book_name_service::update_book_name_info,
            service::book_name_service::update_book_sort_info,
            service::book_name_service::delete_book_name,
            service::book_name_service::book_name_list_to_lable_value,
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
